import { Component, OnInit } from '@angular/core';
import {MatDialog, MAT_DIALOG_DATA} from '@angular/material/dialog';
import {RequestReplyService} from './services/request-reply.service';
import {EventSource, EventService, EventMessage} from './services/event.service';
import {BookedService} from './services/booked.service';
import {User} from './entity/TT';
import { MessageDialogComponent, DialogData } from './dialog/message-dialog/message-dialog.component';
import { ChatService } from './services/chat.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent  implements OnInit {
  title = 'TTWeb';

  me: User;

  loading = false;
  login = false;

  constructor(
    private chatService: ChatService,
    private requestService: RequestReplyService,
    private eventService: EventService,
    private bookedService: BookedService,
    public dialog: MatDialog
    )
    {
      console.log('AppComponent...');
      this.init();
    }

  ngOnInit() {
    console.log('AppComponent ngOnInit...');
  }

  init() {


    this.loading = true;
    this.requestService.GetMe().subscribe((me: User) => {

      setTimeout( () => {
        this.loading = false;
        if (me) {
          this.me = me;
          this.eventService.sendLogin(me);
        } else {
          this.login = true;
        }
      },  400);
      
   });

    this.eventService.subscribeLogin((me: User) => {
      console.log('subscribeLogin', me);
      this.bookedService.refresh();
      this.chatService.init(me);
      return true;
    });


    this.eventService.subscribeExit(() => {
      console.log('subscribeExit ...');
      this.requestService.Logout()
        .subscribe((reply) => {
          if(reply.success){
            this.refresh()
          }
        })
    });

    this.eventService.subscribeEvent((msg: EventMessage) => {
      switch (msg.source) {
        case EventSource.ERROR:
          this.openDialog(msg.data);
          break;
      }
    });

  }

  openDialog(msg: any) {

    const data: DialogData = {message: msg};

    const dialogRef = this.dialog.open(MessageDialogComponent, {
      width: '250px',
      data
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log('The dialog was closed', result);
    });

  }

  refresh(){
    setTimeout(()=>{
      location.href = '/';
    }, 200)
  }

}
